package com.zhiqiang.gameserver.handler;

import com.alibaba.fastjson.JSON;
import com.google.protobuf.InvalidProtocolBufferException;
import com.zhiqiang.gameserver.constant.R;
import com.zhiqiang.gameserver.entity.ZQGameServerEntity;
import com.zhiqiang.gameserver.orm.dao.Account;
import com.zhiqiang.gameserver.orm.dao.Item;
import com.zhiqiang.gameserver.orm.dao.Playerbasicinfo;
import com.zhiqiang.gameserver.orm.dao.Task;
import com.zhiqiang.gameserver.proto.gameServerUserInfo;
import com.zhiqiang.gameserver.util.JedisUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;

import java.util.Date;
import java.util.List;

public class UserInfoMessageHandler extends MessageHandler {
    private static Logger log= LogManager.getLogger(UserInfoMessageHandler.class.getName());
    private Account accountDao =  new Account().dao();
    private Item itemDao = new Item().dao();
    private Playerbasicinfo playerDao = new Playerbasicinfo().dao();
    private Task taskDao = new Task().dao();

    @Override
    public void handleMsg(ZQGameServerEntity msgEntity, List<ZQGameServerEntity> msgList) {
        switch (msgEntity.getMsgType()) {// 根据命令码对应找到对应处理方法
            case R.MessageType.REQUSERLOGIN:
                handleUserLogin(msgEntity, msgList);
                break;
            default:
                System.out.println("找不到对应的命令码");
                log.error("找不到对应的消息类型");

        }
    }

    private void handleUserLogin(ZQGameServerEntity zq, List<ZQGameServerEntity> msgList){
        gameServerUserInfo.ReqUserLogin login=null;
        ZQGameServerEntity rsp = new ZQGameServerEntity();
        try {
            login = gameServerUserInfo.ReqUserLogin.parseFrom(zq.getData());
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
            System.err.println("解码失败");
            log.info("解码失败");
        }
        switch (login.getLoginType()){
            case R.LoginType.MD5LOGIN:
                rsp = LoginByMd5(login.getMd5()+"");
                msgList.add(rsp);
                break;
            case R.LoginType.WECHAT:
                rsp = LoginByMd5(login.getMd5()+"");
                msgList.add(rsp);
                break;
            case R.LoginType.ACCOUNT:
//                todo  太多了，先不写 这里处理账号密码登陆
                break;
            default:
                System.err.println("未找到对应登陆类型！");
                log.error("未找到对应登陆类型");
        }

    }

    private ZQGameServerEntity LoginByMd5(String md5){
        ZQGameServerEntity zq = new ZQGameServerEntity();
        Account account = accountDao.findFirst("select * from zq_account where md5=?",md5);
        if(null==account){
          //不存就创建
            gameServerUserInfo.RspUserLogin rsp = createplayer(md5);
            zq.setLen(R.EncoderAndDecoder.HEADER_LENGTH+rsp.toByteArray().length);
            zq.setMsgType(R.MessageType.RSPUSERLOGIN);
            zq.setResult(R.ERRCode.OK);
            zq.setV6(R.ERRCode.OK);
            zq.setUid(rsp.getUserId());
            zq.setData(rsp.toByteArray());
            return zq;
        }else{
            //存在就放入缓存
            gameServerUserInfo.RspUserLogin rsp = createCache(account);
            zq.setLen(R.EncoderAndDecoder.HEADER_LENGTH+rsp.toByteArray().length);
            zq.setMsgType(R.MessageType.RSPUSERLOGIN);
            zq.setResult(R.ERRCode.OK);
            zq.setV6(R.ERRCode.OK);
            zq.setUid(rsp.getUserId());
            zq.setData(rsp.toByteArray());
            return zq;
        }
    }

    private gameServerUserInfo.RspUserLogin createplayer(String md5){
        Account account = new Account();
        Jedis jedis= JedisUtil.getInstance().getJedis();
        int accountId = Integer.parseInt(jedis.get(R.OrmPara.MAXACCOUNTIDSTRING).toString().trim())+1;
        account.setAccountId(accountId);
        jedis.set(R.OrmPara.MAXACCOUNTIDSTRING,accountId+"");
        account.setAccountName(R.OrmPara.USERCACHEPREFIX+accountId);
        account.setLastLoginTime(new Date());
        account.setLoginType(R.LoginType.MD5LOGIN);
        account.setMd5(md5);
        int userId =  Integer.parseInt(jedis.get(R.OrmPara.MAXUSERIDSTRING).toString().trim())+1;
        account.setUserId(userId);
        account.save();
        Item item = new Item();
        item.setUserId(userId);
        item.setChg(1);
        item.setCur(0);
        item.save();
        Task task =new Task();
        task.setGold(100);
        task.setNextTime(1);
        task.setPoint(10);
        task.setUserId(userId);
        task.save();
        Playerbasicinfo playerInfo = new Playerbasicinfo();
        playerInfo.setUserId(userId);
        playerInfo.setUserLevel(0);
        playerInfo.setUserExp(0);
        playerInfo.setUserName(null);
        playerInfo.setAvatar(1);
        playerInfo.setVipLevel(0);
        playerInfo.setVipPoint(0);
        playerInfo.setGold(100);
        playerInfo.setPoint(0);
        playerInfo.setBornTime(1);
        playerInfo.save();
        gameServerUserInfo.RspUserLogin.Builder rsp = gameServerUserInfo.RspUserLogin.newBuilder();
        gameServerUserInfo.InfoServerTime.Builder st = gameServerUserInfo.InfoServerTime.newBuilder();
        st.setTimeZone(8);//时区
        st.setTodayZero(000);
        st.setNow(12);
        st.setUsec(1);
        rsp.setServerTime(st.build());
        rsp.setUserId(playerInfo.getUserId());
        rsp.setUserName(playerInfo.getUserName());
        rsp.setBornTime(playerInfo.getBornTime());
        rsp.setAvatar(playerInfo.getAvatar());
        rsp.setUserLevel(playerInfo.getUserLevel());
        rsp.setUserExp(playerInfo.getUserExp());
        rsp.setVipLevel(playerInfo.getVipLevel());
        rsp.setVipPoint(playerInfo.getVipPoint());
        rsp.setGold(playerInfo.getGold());
        gameServerUserInfo.InfoItem.Builder infoitem = gameServerUserInfo.InfoItem.newBuilder();
        infoitem.setChg(item.getChg());
        infoitem.setCur(item.getCur());
        infoitem.setGid(item.getId());
        rsp.setItems(0,infoitem);
        gameServerUserInfo.InfoTask.Builder infotask =  gameServerUserInfo.InfoTask.newBuilder();
        infotask.setId(task.getId());
        infotask.setNextTime(task.getNextTime());
        rsp.setTask(infotask);
        String jsonStr = JSON.toJSONString(rsp.build());
        jedis.set(R.OrmPara.USERCACHEPREFIX+accountId+userId,jsonStr);
        JedisUtil.getInstance().returnJedis(jedis);
        return rsp.build();
    }

    public gameServerUserInfo.RspUserLogin createCache(Account account){
        Jedis jedis= JedisUtil.getInstance().getJedis();
        gameServerUserInfo.RspUserLogin.Builder rsp = gameServerUserInfo.RspUserLogin.newBuilder();
        gameServerUserInfo.InfoServerTime.Builder st = gameServerUserInfo.InfoServerTime.newBuilder();
        st.setTimeZone(8);//时区
        st.setTodayZero(000);
        st.setNow(12);
        st.setUsec(1);
        Playerbasicinfo playerInfo = playerDao.findFirst("select * from zq_playerbasicinfo where user_id=?",account.getUserId());
        rsp.setServerTime(st.build());
        rsp.setUserId(playerInfo.getUserId());
        rsp.setUserName(playerInfo.getUserName());
        rsp.setBornTime(playerInfo.getBornTime());
        rsp.setAvatar(playerInfo.getAvatar());
        rsp.setUserLevel(playerInfo.getUserLevel());
        rsp.setUserExp(playerInfo.getUserExp());
        rsp.setVipLevel(playerInfo.getVipLevel());
        rsp.setVipPoint(playerInfo.getVipPoint());
        rsp.setGold(playerInfo.getGold());
        gameServerUserInfo.InfoItem.Builder infoitem = gameServerUserInfo.InfoItem.newBuilder();
        Item item = itemDao.findFirst("select * from zq_item where user_id=?",account.getUserId());
        infoitem.setChg(item.getChg());
        infoitem.setCur(item.getCur());
        infoitem.setGid(item.getId());
        rsp.setItems(0,infoitem);
        gameServerUserInfo.InfoTask.Builder infotask =  gameServerUserInfo.InfoTask.newBuilder();
        Task task = taskDao.findFirst("select * from zq_task where user_id=?",account.getUserId());
        infotask.setId(task.getId());
        infotask.setNextTime(task.getNextTime());
        rsp.setTask(infotask);
        String jsonStr = JSON.toJSONString(rsp.build());
        jedis.set(R.OrmPara.USERCACHEPREFIX+account.getAccountId()+account.getUserId(),jsonStr);
        JedisUtil.getInstance().returnJedis(jedis);
        return rsp.build();
    }
}
